﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Runtime.InteropServices;
using System.Diagnostics;
using Microsoft.Win32;
using System.Collections;

using Leadtools;
using Leadtools.Codecs;
using Leadtools.WinForms;

namespace MINERP.ComControls
{
    public partial class PictureViewer : UserControl
    {
        //属性
        private bool _canSelectMuti=true;
        [Description("分组内的图片能否多选"),Category("行为"),DefaultValue(true)]
        public bool CanSelectMuti
        {
            get { return _canSelectMuti;   }
            set { _canSelectMuti = value; }
        }
        //调用API打开PS
        [DllImport("shell32.dll")]
        public static extern int ShellExecute(int hwnd, string lpszOp, string lpszFile, string lpszParams, string lpszDir, int FsShowCmd);
        public PictureViewer()
        {
            InitializeComponent();
        }

        #region Load方法
        private void UserPic_Load(object sender, EventArgs e)
        {
            cbCanSelectMul.Checked = CanSelectMuti; //能否多选的初始值
        }
        #endregion

        #region 设置能否多选
        //设置能否多选
        private void cbCanSelectMul_CheckedChanged(object sender, EventArgs e)
        {
            SetMultiOrSingleSelection();
        }
        #endregion

        #region 分组内的图片能否多选
        /// <summary>
        /// 分组内的图片能否多选
        /// </summary>
        private void SetMultiOrSingleSelection()
        {
            if (cbCanSelectMul.Checked)
            {
                if (splitContainer1.Panel2.Controls.Count > 0)
                {
                    foreach (Control c in splitContainer1.Panel2.Controls)
                    {
                        Control subC = c.Controls[0];
                        if (subC != null)
                        {
                            RasterThumbnailBrowser browser = (RasterThumbnailBrowser)subC;
                            browser.SelectionMode = RasterImageListSelectionMode.Multi;
                        }
                    }
                }
            }
            else
            {
                if (splitContainer1.Panel2.Controls.Count > 0)
                {
                    foreach (Control c in splitContainer1.Panel2.Controls)
                    {
                        Control subC = c.Controls[0];
                        if (subC != null)
                        {
                            RasterThumbnailBrowser browser = (RasterThumbnailBrowser)subC;
                            browser.SelectionMode = RasterImageListSelectionMode.Single;
                        }
                    }
                }
            }
        }
        #endregion

        #region 设置要加载图片的目录路径集合，这是该控件的外部接口
        /// <summary>
        /// 设置要加载图片的目录路径集合
        /// </summary>
        /// <param name="PhotoPaths">目录集合</param>
        public void SetPhotoPaths(Dictionary<string,string> photoDirectorys)
        {
            //清除控件原有数据
            splitContainer1.Panel2.Controls.Clear();
            totalPhotoNum = 0;
            //根据路径数量,设置GroupBox的个数
            int width = this.splitContainer1.Panel2.Width-6;
            int height = this.splitContainer1.Panel2.Height / photoDirectorys.Count;
            int i = 0;
            foreach (KeyValuePair<string,string> d in photoDirectorys)
            { 
                //动态设置GroupBox
                GroupBox g = new GroupBox();
                g.Text = d.Key;
                g.Width = width;
                g.Height = height-6;
                g.Location = new Point(3,height*i+3);
                g.Anchor = (AnchorStyles.Left | AnchorStyles.Top | AnchorStyles.Right | AnchorStyles.Bottom);
                //在GroupBox内部设置缩略图容器
                PicBrowser b = new PicBrowser();
                b.MouseDoubleClick += new MouseEventHandler(browser_MouseDoubleClick);
                b.MouseDown += new MouseEventHandler(browser_MouseDown);
                b.Dock = DockStyle.Fill;
                GetPhotosInDirectory(d.Value,b);
                g.Controls.Add(b);
                this.splitContainer1.Panel2.Controls.Add(g);
                i++;
            }
            SetMultiOrSingleSelection();    //设置能否多选
            SetPhotoNum();
        }
        
        #endregion

        #region 设置图片总数量
        int totalPhotoNum = 0;
        /// <summary>
        /// 设置图片总数量
        /// </summary>
        private void SetPhotoNum()
        {
            lblTotalPhoto.Text = totalPhotoNum.ToString();
        }
        #endregion

        #region 加载单个目录下所有的图片
        /// <summary>
        /// 加载单个目录下所有的图片
        /// </summary>
        /// <param name="directory">目录路径</param>
        public void GetPhotosInDirectory(string directory,PicBrowser browser)
        {
            if (Directory.Exists(directory))
            {
                DirectoryInfo dInfo = new DirectoryInfo(directory);
                DirectoryInfo[] dSubInfos = dInfo.GetDirectories();
                FileInfo[] fSubInfos = dInfo.GetFiles();
                foreach (DirectoryInfo dSubInfo in dSubInfos)
                {
                    GetPhotosInDirectory(dSubInfo.FullName,browser);
                }
                foreach (FileInfo fSubInfo in fSubInfos)
                {
                    AddSinglePhoto(fSubInfo.FullName,browser);
                }
            }
        }
        /// <summary>
        /// 设置要加载图片的目录路径集合 不遍历
        /// </summary>
        /// <param name="PhotoPaths">目录集合</param>
        public void SetPhotoPath(Dictionary<string, string> photoDirectorys)
        {
            //清除控件原有数据
            splitContainer1.Panel2.Controls.Clear();
            totalPhotoNum = 0;
            //根据路径数量,设置GroupBox的个数
            int width = this.splitContainer1.Panel2.Width - 6;
            int height = this.splitContainer1.Panel2.Height / photoDirectorys.Count;
            int i = 0;
            foreach (KeyValuePair<string, string> d in photoDirectorys)
            {
                //动态设置GroupBox
                GroupBox g = new GroupBox();
                g.Text = d.Key;
                g.Width = width;
                g.Height = height - 6;
                g.Location = new Point(3, height * i + 3);
                g.Anchor = (AnchorStyles.Left | AnchorStyles.Top | AnchorStyles.Right | AnchorStyles.Bottom);
                //在GroupBox内部设置缩略图容器
                PicBrowser b = new PicBrowser();
                b.MouseDoubleClick += new MouseEventHandler(browser_MouseDoubleClick);
                b.MouseDown += new MouseEventHandler(browser_MouseDown);
                b.Dock = DockStyle.Fill;
                GetPhotoInDirectory(d.Value, b);
                g.Controls.Add(b);
                this.splitContainer1.Panel2.Controls.Add(g);
                i++;
            }
            SetMultiOrSingleSelection();    //设置能否多选
            SetPhotoNum();
        }
        
        /// <summary>
        /// 加载单个目录下所有的图片不遍历
        /// </summary>
        /// <param name="directory">目录路径</param>
        public void GetPhotoInDirectory(string directory, PicBrowser browser)
        {
            if (Directory.Exists(directory))
            {
                DirectoryInfo dInfo = new DirectoryInfo(directory);
                DirectoryInfo[] dSubInfos = dInfo.GetDirectories();
                FileInfo[] fSubInfos = dInfo.GetFiles();
               
                foreach (FileInfo fSubInfo in fSubInfos)
                {
                    AddSinglePhoto(fSubInfo.FullName, browser);
                }
            }
        }
        #endregion

        #region 加载图片的具体过程
        /// <summary>
        /// 加载单个图片
        /// </summary>
        /// <param name="photoPath">图片路径</param>
        public void AddSinglePhoto(string photoPath,PicBrowser browser)
        {
            try
            {
                RasterCodecs.Startup();
                RasterCodecs codecs = new RasterCodecs();
                CodecsThumbnailOptions options = new CodecsThumbnailOptions();
                options.Resample = true;
                options.LoadStamp = true;
                options.MaintainAspectRatio = true;
                RasterImage img;
                try
                {
                    img = codecs.ReadThumbnail(photoPath, options, 1);
                }
                catch
                {
                    //为图片设置Stamp
                    RasterImage imgInfo = codecs.Load(photoPath);
                    Rectangle rc = RasterImage.CalculatePaintModeRectangle(imgInfo.Width, imgInfo.Height, new Rectangle(0, 0, 128, 128), RasterPaintSizeMode.FitAlways, RasterPaintAlignMode.Near, RasterPaintAlignMode.Near);
                    codecs.Options.Jpeg.Save.StampWidth = rc.Width;
                    codecs.Options.Jpeg.Save.StampHeight = rc.Height;
                    codecs.Options.Jpeg.Save.SaveWithStamp = true;
                    codecs.Options.Jpeg.Save.StampBitsPerPixel = 24;
                    codecs.Save(imgInfo, photoPath, RasterImageFormat.Jpeg, 0);
                    //重新读缩略图
                    img = codecs.ReadThumbnail(photoPath, options, 1);
                }
                int index = photoPath.LastIndexOf("\\");
                string fileName = photoPath.Substring(index + 1);
                RasterImageListItem item = new RasterImageListItem(img, 1, fileName);
                item.Tag = photoPath;
                browser.Items.Add(item);
                totalPhotoNum++;    //图片总数量加1
            }
            catch { return; }
        }
        #endregion

        #region 打开PS的按钮
        //打开PS的按钮
        private void btnOpenPS_Click(object sender, EventArgs e)
        {
            OpenPS();
        }
        #endregion

        #region 打开PS
        /// <summary>
        /// 打开PS
        /// </summary>
        private void OpenPS()
        {
            //操作注册表
            RegistryKey userPhotoShopKey = Registry.CurrentUser.OpenSubKey("userPhotoShopKey", true);
            string psPath="";
            if (userPhotoShopKey != null)
                psPath = userPhotoShopKey.GetValue("psPhoto", "").ToString();
            //psPath = Properties.Settings.Default.PhotoShopPath;
            int r1 = 0;
            try
            {
                r1 = ShellExecute(0, "open", "Photoshop.exe", null, psPath, 1);
            }
            catch
            {
                r1 = 0;
            }
            if (r1 == 0)
            {
                int r = ShellExecute(0, "open", "Photoshop.exe", null, "", 1);
                if (r == 0)
                {
                    MessageBox.Show("PhotoShop的路径不正确,请重新设置", "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
                    {
                        string newPsPath = folderBrowserDialog1.SelectedPath;
                        //SetPSPath(newPsPath);
                        if (userPhotoShopKey == null)
                            userPhotoShopKey = Registry.CurrentUser.CreateSubKey("userPhotoShopKey");
                        userPhotoShopKey.SetValue("psPhoto", newPsPath);
                        int r3 = ShellExecute(0, "open", "Photoshop.exe", null, newPsPath, 1);
                        if (r3 == 0)
                        {
                            MessageBox.Show("不能打开PhotoShop,请确认是否已正确安装!", "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        }
                    }
                }
            }
            if(userPhotoShopKey!=null)
                userPhotoShopKey.Close();
        }
        #endregion

        #region 从缩略图拖图片到PS
        string[] files;
        DateTime previous=DateTime.Now; //上次点击的时间
        //拖曳操作
        private void browser_MouseDown(object sender, MouseEventArgs e)
        {
            DateTime now = DateTime.Now;
            TimeSpan span = now - previous;
            previous = now;
            if (span.Minutes == 0 && span.Seconds == 0 && span.Milliseconds <= 300&&e.Button==MouseButtons.Left)
            {
                browser_MouseDoubleClick(sender, e);    //执行双击事件
                return; //如果执行了双击事件,就不再执行拖曳事件
            }
            PicBrowser browser = (PicBrowser)sender;
            if(browser._list.Count>0&&e.Button==MouseButtons.Right)
            {
                //files = new string[browser.SelectedItems.Count];   //这里用字符串不能实现拖曳,用字符串数组可以
                files = new string[browser._list.Count]; 
                for (int i = 0; i < browser._list.Count; i++)
                {
                    files[i] = browser._list[i].Tag.ToString();
                }
                DataObject data = new DataObject();
                data.SetData(DataFormats.FileDrop, files);
                DoDragDrop(data, DragDropEffects.All);
            }
        }
        #endregion

        #region 鼠标双击,打开PS,将选中的图片复制到PS
        //鼠标双击,打开PS,将选中的图片复制到PS
        private void browser_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            try
            {
                if (e.Button == MouseButtons.Left)
                {
                    OpenPS();
                    PicBrowser browser = (PicBrowser)sender;
                    //复制选中的图片到PS
                    if (browser.SelectedItems.Count > 0)
                    {
                        string psPhoto = browser.SelectedItems[0].Tag.ToString();
                        Process.Start("Photoshop.exe", psPhoto);
                    }
                }
            }
            catch (Exception)
            {

              //throw new Exception();
            }
        }
        #endregion

        #region 随着用户控件大小的变化,调整GroupBox的大小
        //调整GroupBox的大小
        private void UserPic_Resize(object sender, EventArgs e)
        {
            if (this.splitContainer1.Panel2.Controls.Count > 1)
            {
                int height = this.splitContainer1.Panel2.Height/this.splitContainer1.Panel2.Controls.Count;
                //第一个GroupBox定位
                for (int i = 0; i < this.splitContainer1.Panel2.Controls.Count; i++)
                {
                    this.splitContainer1.Panel2.Controls[i].Location = new Point(3, height * i + 3);
                    this.splitContainer1.Panel2.Controls[i].Height = height-6;
                }
            }
        }
        #endregion

    }
}
